using LightCAD.MathLib;
using System;
using System.Collections;
using System.Collections.Generic;

namespace LightCAD.Three
{
    public class SplineCurve : Curve<Vector2>
    {
        #region Properties

        public ListEx<Vector2> points;

        #endregion

        #region constructor
        public SplineCurve(ListEx<Vector2> points = null)
        {
            if (points == null) points = new ListEx<Vector2>();
            this.type = "SplineCurve";
            this.points = points;
        }
        #endregion

        #region methods
        public override Vector2 getPoint(double t, Vector2 optionalTarget = null)
        {
            if (optionalTarget == null) optionalTarget = new Vector2();
            var point = optionalTarget;
            var points = this.points;
            var p = (points.Length - 1) * t;
            var intPoint = (int)Math.Floor(p);
            var weight = p - intPoint;
            var p0 = points[intPoint == 0 ? intPoint : intPoint - 1];
            var p1 = points[intPoint];
            var p2 = points[intPoint > points.Length - 2 ? points.Length - 1 : intPoint + 1];
            var p3 = points[intPoint > points.Length - 3 ? points.Length - 1 : intPoint + 2];
            point.Set(
                Interpolations.CatmullRom(weight, p0.X, p1.X, p2.X, p3.X),
                Interpolations.CatmullRom(weight, p0.Y, p1.Y, p2.Y, p3.Y)
            );
            return point;
        }
        public override Curve<Vector2> copy(Curve<Vector2> source)
        {
            return copy(source as SplineCurve);
        }
        public SplineCurve copy(SplineCurve source)
        {
            base.copy(source);
            this.points = new ListEx<Vector2>();
            for (int i = 0, l = source.points.Length; i < l; i++)
            {
                var point = source.points[i];
                this.points.Push(point.Clone());
            }
            return this;
        }

        public override Curve<Vector2> clone()
        {
            return new SplineCurve().copy(this);
        }

        #endregion

    }
}
